package ph.h.audiobook;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException;

import ph.h.Helper.TextHelper;
import ph.h.Helper.XMLHelper;
import ph.h.model.Sentence;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity {
	private EditText txtMain;
	private MediaPlayer player;
	final private String rootFolder = "audiobooks";
	final private String audioFoler = "audio";
	final private String booksFolder = "books";
	final private String mappingFoler = "mapping";
	final private String videosFoler = "videos";
	
	private int name_book = 0;
	private int displayPosition = 0;

	Sentence senStart = null;
	Sentence senEnd = null;

	@SuppressLint({ "ShowToast", "NewApi" })
	public void onClick(View v) {
		txtMain = (EditText) findViewById(R.id.txtMain);
		int positon = txtMain.getSelectionStart();
		if (positon < txtMain.getText().length()) {
			for (int i = 0; i < TextHelper.getEndSentenceSignals().length; i++) {
				if (TextHelper.getEndSentenceSignals()[i].equals(Character
						.toString(txtMain.getText().charAt(positon)))) {
					if (positon > 0) {
						positon--;
					} else {
						positon++;
					}
					break;
				}
			}
		} else {
			positon = txtMain.getText().length() - 1;
		}
		Sentence sentence = TextHelper.findSentence(positon, txtMain.getText()
				.toString());
		if (sentence != null) {
			txtMain.setText(TextHelper.changeSentenceColor(txtMain.getText()
					.toString(), sentence.getStart(), sentence.getEnd()));
			txtMain.setSelection(positon);
		}

		// Phu
		// Phat audio
		//
		if (senStart != null) {
			try {
				senEnd = XMLHelper.getTimeMapping(sentence.getOrder(),
						rootFolder + "/" + mappingFoler,
						"Kinh_So_Chua");
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			TextHelper.PlayAudio(senStart, senEnd, player);
			senStart = null;
			senEnd = null;
		} else if (senEnd == null) {
			try {
				senStart = XMLHelper.getTimeMapping(sentence.getOrder(),
						rootFolder + "/" + mappingFoler,
						"Kinh_So_Chua");
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	
	
	}

	@SuppressLint({ "ShowToast", "SdCardPath" })
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// create MediaPlayer player
		player = new MediaPlayer();
		// create folder structure in first time
		if (!checkDirs()) {
			Toast.makeText(getApplicationContext(), "Cannot find resources",
					3000);
		}
		String name = "Khong_nao_son.txt"; 
		setbook(name_book);
		if (name_book == 0)
			name ="Khong_nao_son.txt";
		if (name_book == 1)
			name = "Bahasa_Relentless.txt";
		if (name_book == 2)
			name = "kinh_so_chua.txt";
		// get TextView
		txtMain = (EditText) findViewById(R.id.txtMain);
		txtMain.setText(readTxt(rootFolder + "/" + booksFolder + "/"
				+ name));

		player = readAudio(rootFolder + "/" + audioFoler + "/"
				+ "Kinh_So_Chua.mp3");

		// Phu
		//btnStop
		Button btnStop = (Button) findViewById(R.id.btnStop);

		btnStop.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				player.stop();
			}
		});
		
		// Phu
				// btn play video
				Button ibtPlayVideo = (Button) findViewById(R.id.btnPlayvideo);

				ibtPlayVideo.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						player.stop();
						Intent intent = new Intent(MainActivity.this,
								VideoActivity.class);
						startActivity(intent);
					}
				});
		
		
		//H
		//move cursor to position
		int position = XMLHelper.getPosition(rootFolder + "/" + mappingFoler,
						"Kinh_So_Chua");
		txtMain.setSelection(position);
		
	
	}

	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
    protected void onActivityResult(int requestCode,
                                     int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
         	 name_book = data.getExtras().getInt("songIndex");
         	 // play selected song
         	 setbook(name_book);
        }
 
    }
	
	public void setbook(int name) {
		
		name_book = name;
		
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@SuppressLint("SdCardPath")
	private boolean checkDirs() {
		boolean success = true;
		try {
			// root
			File root = new File(Environment.getExternalStorageDirectory(),
					rootFolder);
			if (!root.exists()) {
				if (root.mkdir()) {
					success = false;
				}
			}
			// audio
			File audio = new File(Environment.getExternalStorageDirectory(),
					rootFolder + "/" + audioFoler);
			if (!audio.exists()) {
				if (audio.mkdir()) {
					success = false;
				}
			}
			// books
			File books = new File(Environment.getExternalStorageDirectory(),
					rootFolder + "/" + booksFolder);
			if (!books.exists()) {
				if (books.mkdir()) {
					success = false;
				}
			}
			// mapping
			File mapping = new File(Environment.getExternalStorageDirectory(),
					rootFolder + "/" + mappingFoler);
			if (!mapping.exists()) {
				if (!mapping.mkdir()) {
					success = false;
				}
			}

			// video -Phu
			File video = new File(Environment.getExternalStorageDirectory(),
					rootFolder + "/" + videosFoler);
			if (!video.exists()) {
				if (!video.mkdir()) {
					success = false;
				}
			}

		} catch (Exception e) {
			success = false;
		}
		return success;
	}

	@SuppressWarnings("resource")
	private String readTxt(String path) {
		// Get the text file
		File file = new File(Environment.getExternalStorageDirectory(), path);
		// Read text from file
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;

			while ((line = br.readLine()) != null) {
				text.append(line.trim());
				text.append('\n');
			}
		} catch (IOException e) {
			return e.getMessage();
		}
		while (text.toString().indexOf("\n ") != -1) {
		}
		return text.toString();
	}

	private MediaPlayer readAudio(String path) {

		File file = new File(Environment.getExternalStorageDirectory(), path);
		try {
			FileInputStream fis = new FileInputStream(file);
			if (file.exists()) {
				player.setDataSource(fis.getFD());
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return player;
	}

	private boolean doubleBackToExitPressedOnce = false;

	@Override
	protected void onResume() {
		super.onResume();
		// .... other stuff in my onResume ....
		this.doubleBackToExitPressedOnce = false;
	}

	@Override
	public void onBackPressed() {
		if (doubleBackToExitPressedOnce) {
			super.onBackPressed();
			
			//get current position
			displayPosition = txtMain.getSelectionStart();
			try {
				XMLHelper.updatePosition(rootFolder + "/" + mappingFoler,
							"Kinh_So_Chua", displayPosition);
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
			System.exit(0);
			return;
		}
		this.doubleBackToExitPressedOnce = true;
		Toast.makeText(this, "Press back again to exit!",
				Toast.LENGTH_SHORT).show();
	}
}
